import { components } from '@/types/ApiInterface'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface UserInfo {
  id: string
  username: string
  phone: string
  communities: components['schemas']['CommunityUserStatus'][]
  imgUrl?: string
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const currentCommunity = ref<components['schemas']['CommunityUserStatus'] | null>(null)

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    uni.setStorageSync('userInfo', info)
  }

  const setCurrentCommunity = (community: components['schemas']['CommunityUserStatus']) => {
    currentCommunity.value = community
    // 可以选择将当前选中的小区信息保存到本地存储
    uni.setStorageSync('currentCommunity', community)
  }

  const clearUserInfo = () => {
    userInfo.value = null
    currentCommunity.value = null
    uni.removeStorageSync('currentCommunity')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('token')
    uni.reLaunch({
      url: '/pages/login/index',
    })
  }

  const clearCurrentCommunity = () => {
    currentCommunity.value = null
    uni.removeStorageSync('currentCommunity')
  }

  const isAdmin = computed(() => {
    if (!currentCommunity.value) return false
    return ['ADMIN', 'PMC_WORKER'].includes(currentCommunity.value.role)
  })

  return {
    userInfo,
    currentCommunity,
    setUserInfo,
    setCurrentCommunity,
    clearUserInfo,
    clearCurrentCommunity,
    isAdmin,
  }
})
